#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Vergil
# datetime:2018/9/22 21:09
# software: PyCharm
import pytesseract
from pytesseract import image_to_string
import urllib.request as req
import requests
import os
import json

from PIL import Image


def captcha_download(captcha_url, cookies):
    url = captcha_url
    headers = {
        'Cookie': 'CASPRIVACY=""; TGC=""; JSESSIONID=%s' % cookies
    }
    path = os.path.abspath('.')
    os.chdir(path + '/images')
    img_path = os.path.abspath('.')
    r = requests.get(url, headers=headers)

    with open('./captcha.jpg', 'wb') as f:
        f.write(r.content)

    captcha = captcha_distinguish(img_path)
    os.chdir(path)
    return captcha


def captcha_distinguish(img_path):
    img = Image.open(img_path + '/captcha.jpg')
    img = img.convert('L')

    threshold = 140
    table = []

    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)

    out = img.point(table, '1')
    out.save(img_path + '/captcha.jpg')
    captcha = image_to_string(out)

    return captcha


def _test(cookies):
    c = requests.get(
        'https://spoc.tfswufe.edu.cn/',
        cookies={
            'name': 'JSESSIONID',
            'value': cookies})
    print(c.cookies)


def main(captcha_url, cookies):
    captcha = captcha_download(captcha_url, cookies)

    return captcha
